<template>
  <div>
    <a-row>
      <a-button type="primary" @click="showModal(false)">新增</a-button>
      <a-button type="primary" @click="showModal(true)">修改</a-button>
      <a-button type="danger" @click="removeApp">删除</a-button>
      <a-button type="primary" @click="showPortModal">映射端口</a-button>
      <a-button type="primary" @click="showConfigItemModal">环境变量</a-button>
      <a-button type="primary" @click="syncState">同步状态</a-button>
      <a-select @change="handleEnvChange" style="width: 100px" placeholder="环境">
        <a-select-option v-for="env in envList" :key="env.id">{{env.name}}</a-select-option>
      </a-select>

    </a-row>
    <a-row>
      <a-col :span="24">
        <a-table :columns="grid.columns"
                 :rowKey="record => record.id"
                 :dataSource="grid.data"
                 :pagination="grid.pagination"
                 :loading="loading"
                 @change="handleTableChange"
                 :rowSelection="grid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-col>
    </a-row>

    <!--新增部署-->
    <a-modal
      title="部署信息"
      :maskClosable="false"
      :visible="visible"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="form">
        <a-form-item
          label="应用"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-select
            style="width: 100%" v-decorator="[
            'appId',{rules: [{ required: true, message: '请选择应用' }]}
            ]">
            <a-select-option v-for="app in appList" :key="app.id">{{app.app}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="环境"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-select
            style="width: 100%" v-decorator="[
            'envId',{rules: [{ required: true, message: '请选择环境' }]}
            ]">
            <a-select-option v-for="env in envList" :key="env.id">{{env.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="镜像"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'image',{rules: [{validator:validateImage}]}]"
          />
        </a-form-item>
        <a-form-item
          label="版本"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'packageVersion',
          {rules: [{validator:validateImage}]}
        ]"
          />
        </a-form-item>
        <a-form-item
          label="使用适配器"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-radio-group name="useAdapter" v-decorator="[
          'useAdapter',
          {rules: [{ required: true, message: '请选择是否使用适配器'}]}
        ]">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="健康检查"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-radio-group name="healthCheck" v-decorator="[
          'healthCheck',
          {rules: [{ required: true, message: '请选择是否使用健康检查'}]}
        ]">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="实例数"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'replicas',
          {rules: [
            { required: true, message: '请输入实例数量' },
            { type: 'integer', message: '使用数字格式',
              transform(value) {
                      if(value){
                        return Number(value);
                      }
                    }
             }
          ]}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>


    <!--端口列表-->
    <a-modal
      title="映射端口列表"
      :maskClosable="false"
      :visible="mappingPortVisible"
      @cancel="mappingPortHandleCancel"
      :destroyOnClose="true"
    >

      <a-row>
        <a-button type="primary" @click="showEditPortModal(false)">新增</a-button>
        <a-button type="primary" @click="showEditPortModal(true)">修改</a-button>
        <a-button type="danger" @click="removePort">删除</a-button>
      </a-row>
      <a-row>
        <a-table :columns="portGrid.columns"
                 :rowKey="record => record.id"
                 :dataSource="portGrid.data"
                 :pagination="portGrid.pagination"
                 :loading="portGrid.loading"
                 @change="handlePortTableChange"
                 :rowSelection="portGrid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-row>
      <template slot="footer">
        <a-button key="back" @click="mappingPortHandleCancel">关闭</a-button>
</template>
</a-modal>

    <!--编辑端口-->
    <a-modal
      title="映射端口"
      :maskClosable="false"
      :visible="editPortVisible"
      @ok="handleEditPortOk"
      @cancel="editPortHandleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="portForm">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入名称' }]}]"
          />
        </a-form-item>
        <a-form-item
          label="内部端口"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'port',
          {rules: [
            { required: true, message: '请输入内部端口' },
            { type: 'integer', message: '使用数字格式',
              transform(value) {
                      if(value){
                        return Number(value);
                      }
                    }
             }
          ]}]"
          />
        </a-form-item>
        <a-form-item
          label="外部端口"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'mappingPort',
          {rules: [
            { required: false},
            { type: 'integer', message: '使用数字格式',
              transform(value) {
                      if(value){
                        return Number(value);
                      }
                    }
             }
          ]}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>


    <!--环境变量列表-->
    <a-modal
      title="环境变量列表"
      :maskClosable="false"
      :visible="configItemVisible"
      @cancel="configItemHandleCancel"
      :destroyOnClose="true"
    >

      <a-row>
        <a-button type="primary" @click="showEditConfigItemModal(false)">新增</a-button>
        <a-button type="primary" @click="showEditConfigItemModal(true)">修改</a-button>
        <a-button type="danger" @click="removeConfigItem">删除</a-button>
      </a-row>
      <a-row>
        <a-table :columns="configItemGrid.columns"
                 :rowKey="record => record.id"
                 :dataSource="configItemGrid.data"
                 :pagination="configItemGrid.pagination"
                 :loading="configItemGrid.loading"
                 @change="handleConfigItemTableChange"
                 :rowSelection="configItemGrid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-row>
      <template slot="footer">
        <a-button key="back" @click="configItemHandleCancel">关闭</a-button>
      </template>
    </a-modal>

    <!--编辑环境列表-->
    <a-modal
      title="编辑环境列表"
      :maskClosable="false"
      :visible="editConfigItemVisible"
      @ok="handleEditConfigItemOk"
      @cancel="editConfigItemHandleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="configItemForm">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入名称' }]}]"
          />
        </a-form-item>
        <a-form-item
          label="值"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'value',
          {rules: [{ required: true, message: '请输入值' }]}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
    import {getFetch, postFetch} from '@/util/fetch';

    export default {
        mounted() {
            this.fetch();
            this.initAppList();
            this.initEnvList();
        },
        data() {
            return {
                editPortVisible: false,
                mappingPortVisible: false,
                editConfigItemVisible: false,
                configItemVisible: false,
                useAdapter: false,
                healthCheck: false,
                appList: [],
                envList: [],
                grid: {
                    columns: [
                        {
                            title: 'ID',
                            dataIndex: 'id'
                        }, {
                            title: '应用',
                            dataIndex: 'app',
                            customRender: (text, row, index) => {
                                if (row.app) {
                                    return row.app.app
                                } else {
                                    return null;
                                }
                            }
                        }, {
                            title: '环境',
                            dataIndex: 'env',
                            customRender: (text, row, index) => {
                                if (row.env) {
                                    return row.env.name
                                } else {
                                    return null;
                                }
                            }
                        }, {
                            title: '镜像',
                            dataIndex: 'image',
                        }, {
                            title: '版本',
                            dataIndex: 'packageVersion',
                        }, {
                            title: '使用适配器',
                            dataIndex: 'useAdapter',
                            customRender: (text, row, index) => {
                                return row.useAdapter ? "是" : "否"
                            }
                        }, {
                            title: '健康检查',
                            dataIndex: 'healthCheck',
                            customRender: (text, row, index) => {
                                return row.healthCheck ? "是" : "否"
                            }
                        }, {
                            title: '实例数',
                            dataIndex: 'replicas',
                        }, {
                            title: '状态',
                            dataIndex: 'state',
                        }, {
                            title: '重启次数',
                            dataIndex: 'restartNum',
                        }, {
                            title: 'pod状态',
                            dataIndex: 'podState',
                            customRender: (text, row, index) => {
                                return row.runContainerNum + "/" + row.containerTotal;
                            }
                        }
                    ],
                    data: [],
                    selectedRows: [],
                    rowSelection: {
                        type: "radio",
                        selectedRowKeys: [],
                        onChange: this.onSelectChange,
                    },
                    pagination: {
                        pageSize: 10,
                        current: 1
                    },
                    params: ""
                },
                portGrid: {
                    columns: [
                        {
                            title: 'ID',
                            dataIndex: 'id'
                        }, {
                            title: '名称',
                            dataIndex: 'name',
                        }, {
                            title: '内部端口',
                            dataIndex: 'port',
                        }, {
                            title: '外部端口',
                            dataIndex: 'mappingPort',
                        }
                    ],
                    data: [],
                    selectedRows: [],
                    rowSelection: {
                        type: "radio",
                        selectedRowKeys: [],
                        onChange: this.onPortSelectChange,
                    },
                    pagination: {
                        pageSize: 10,
                        current: 1
                    },
                },
                configItemGrid: {
                    columns: [
                        {
                            title: 'ID',
                            dataIndex: 'id'
                        }, {
                            title: '名称',
                            dataIndex: 'name',
                        }, {
                            title: '值',
                            dataIndex: 'value',
                        }
                    ],
                    data: [],
                    selectedRows: [],
                    rowSelection: {
                        type: "radio",
                        selectedRowKeys: [],
                        onChange: this.onConfigItemSelectChange,
                    },
                    pagination: {
                        pageSize: 10,
                        current: 1
                    },
                },
                form: this.$form.createForm(this),
                portForm: this.$form.createForm(this),
                configItemForm: this.$form.createForm(this),
                loading: false,
                ModalText: 'Content of the modal',
                visible: false,
                confirmLoading: false,
                editApp: false,
                editConfigItem: false
            }
        },
        methods: {
            validateImage(rule, value, callback) {
                const form = this.form;
                if ((form.getFieldValue("packageVersion")) || (form.getFieldValue("image"))) {
                    callback();
                } else {
                    callback("包版本和镜像地址至少填写一个");
                }
            },
            initAppList() {
                let that = this;
                getFetch("/api/app?pageable=false").then((data) => {
                    that.appList = data.data.content;
                });
            },
            initEnvList() {
                let that = this;
                getFetch("/api/env?pageable=false").then((data) => {
                    that.envList = data.data.content;
                });
            },
            handleEnvChange(value) {
                this.grid.params = "env.id=" + value;
                this.fetch();
            },
            showPortModal() {
                let that = this;
                if (this.grid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                that.mappingPortVisible = true;
                that.fetchMappingPort();
            },
            showConfigItemModal() {
                let that = this;
                if (this.grid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                that.configItemVisible = true;
                that.fetchConfigItem();
            },
            syncState() {
                let that = this;
                getFetch("/api/appEnv/syncstate").then((data) => {
                    that.fetch();
                    this.$message.info("同步成功");
                });
            },
            removeApp() {
                if (this.grid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                let that = this;
                this.$confirm({
                    title: '确认',
                    content: '你确认要删除吗?',
                    onOk() {
                        getFetch("/api/appEnv/" + that.grid.selectedRows[0].id + "/delete").then((data) => {
                            that.fetch();
                        });
                    },
                    onCancel() {
                    },
                });
            },
            removePort() {
                if (this.portGrid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                let that = this;
                this.$confirm({
                    title: '确认',
                    content: '你确认要删除吗?',
                    onOk() {
                        getFetch("/api/appEnvPort/" + that.portGrid.selectedRows[0].id + "/delete").then((data) => {
                            that.fetchMappingPort();
                        });
                    },
                    onCancel() {
                    },
                });
            },
            removeConfigItem() {
                if (this.configItemGrid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                let that = this;
                this.$confirm({
                    title: '确认',
                    content: '你确认要删除吗?',
                    onOk() {
                        getFetch("/api/appEnvConfigItem/" + that.configItemGrid.selectedRows[0].id + "/delete").then((data) => {
                            that.fetchConfigItem();
                        });
                    },
                    onCancel() {
                    },
                });
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.grid.selectedRows = selectedRows;
                this.grid.rowSelection.selectedRowKeys = selectedRowKeys;
            },
            onPortSelectChange(selectedRowKeys, selectedRows) {
                this.portGrid.selectedRows = selectedRows;
                this.portGrid.rowSelection.selectedRowKeys = selectedRowKeys;
            },
            onConfigItemSelectChange(selectedRowKeys, selectedRows) {
                this.configItemGrid.selectedRows = selectedRows;
                this.configItemGrid.rowSelection.selectedRowKeys = selectedRowKeys;
            },
            showDeployModal() {
                let that = this;
                if (this.grid.selectedRows.length === 0) {
                    this.$message.warn("请选中行");
                    return;
                } else if (this.grid.selectedRows.length > 1) {
                    this.$message.warn("请选中一行");
                    return;
                } else {
                    let row = this.grid.selectedRows[0];
                    setTimeout(() => {
                        this.form.setFieldsValue({
                            app: row.app,
                            remark: row.remark
                        });
                    }, 0);
                }
                that.deployVisible = true;
            },
            showModal(edit) {
                if (edit) {
                    this.editApp = true;
                    if (this.grid.selectedRows.length === 0) {
                        this.$message.warn("请选中行");
                        return;
                    } else if (this.grid.selectedRows.length > 1) {
                        this.$message.warn("请选中一行");
                        return;
                    } else {
                        let row = this.grid.selectedRows[0];
                        setTimeout(() => {
                            this.form.setFieldsValue({
                                appId: row.app.id,
                                image: row.image,
                                envId: row.env.id,
                                packageVersion: row.packageVersion,
                                healthCheck: row.healthCheck,
                                useAdapter: row.useAdapter,
                                replicas: row.replicas
                            });
                        }, 0);
                    }
                } else {
                    this.editApp = false;
                    this.form.resetFields();
                }
                this.visible = true
            },
            showEditPortModal(edit) {
                if (edit) {
                    this.editPort = true;
                    if (this.portGrid.selectedRows.length === 0) {
                        this.$message.warn("请选中行");
                        return;
                    } else if (this.portGrid.selectedRows.length > 1) {
                        this.$message.warn("请选中一行");
                        return;
                    } else {
                        let row = this.portGrid.selectedRows[0];
                        setTimeout(() => {
                            this.portForm.setFieldsValue({
                                name: row.name,
                                port: row.port,
                                mappingPort: row.mappingPort
                            });
                        }, 0);
                    }
                } else {
                    this.editPort = false;
                    this.portForm.resetFields();
                }
                this.editPortVisible = true
            },
            showEditConfigItemModal(edit) {
                if (edit) {
                    this.editConfigItem = true;
                    if (this.configItemGrid.selectedRows.length === 0) {
                        this.$message.warn("请选中行");
                        return;
                    } else if (this.configItemGrid.selectedRows.length > 1) {
                        this.$message.warn("请选中一行");
                        return;
                    } else {
                        let row = this.configItemGrid.selectedRows[0];
                        setTimeout(() => {
                            this.configItemForm.setFieldsValue({
                                name: row.name,
                                value: row.value
                            });
                        }, 0);
                    }
                } else {
                    this.editConfigItem = false;
                    this.configItemForm.resetFields();
                }
                this.editConfigItemVisible = true
            },
            handleOk(e) {
                console.log("------");
                e.preventDefault();
                const that = this;
                this.form.validateFields((err, values) => {
                    if (!err) {
                        if (this.editApp) {
                            values.id = this.grid.selectedRows[0].id;
                        }
                        let url = "/api/appEnv";
                        if (this.editApp) {
                            url += "/update";
                        }
                        for (let i = 0; i < that.appList.length; i++) {
                            if (that.appList[i].id === values.appId) {
                                values.app = that.appList[i];
                                break;
                            }
                        }
                        for (let i = 0; i < that.envList.length; i++) {
                            if (that.envList[i].id === values.envId) {
                                values.env = that.envList[i];
                                break;
                            }
                        }
                        postFetch(url, values).then((data) => {
                            this.form.resetFields();
                            this.visible = false;
                            this.fetch();
                            this.grid.rowSelection.selectedRowKeys = [];
                            this.grid.selectedRows = [];
                        });
                    } else {
                        this.$message.error("字段有错误");
                    }
                });
            },
            handleCancel(e) {
                console.log('Clicked cancel button');
                this.visible = false;
            },
            handleEditPortOk(e) {
                console.log("------");
                e.preventDefault();
                const that = this;
                this.portForm.validateFields((err, values) => {
                    if (!err) {
                        if (this.editPort) {
                            values.id = this.portGrid.selectedRows[0].id;
                        }
                        let url = "/api/appEnvPort";
                        if (this.editPort) {
                            url += "/update";
                        }
                        values.appEnv = that.grid.selectedRows[0];
                        postFetch(url, values).then((data) => {
                            this.portForm.resetFields();
                            this.editPortVisible = false;
                            this.fetchMappingPort();
                            this.portGrid.rowSelection.selectedRowKeys = [];
                            this.portGrid.selectedRows = [];
                        });
                    } else {
                        this.$message.error("字段有错误");
                    }
                });
            },
            handleEditConfigItemOk(e) {
                console.log("------");
                e.preventDefault();
                const that = this;
                this.configItemForm.validateFields((err, values) => {
                    if (!err) {
                        if (this.editConfigItem) {
                            values.id = this.configItemGrid.selectedRows[0].id;
                        }
                        let url = "/api/appEnvConfigItem";
                        if (this.editConfigItem) {
                            url += "/update";
                        }
                        values.appEnv = that.grid.selectedRows[0];
                        postFetch(url, values).then((data) => {
                            this.configItemForm.resetFields();
                            this.editConfigItemVisible = false;
                            this.fetchConfigItem();
                            this.configItemGrid.rowSelection.selectedRowKeys = [];
                            this.configItemGrid.selectedRows = [];
                        });
                    } else {
                        this.$message.error("字段有错误");
                    }
                });
            },
            mappingPortHandleCancel(e) {
                console.log('Clicked cancel button');
                this.mappingPortVisible = false;
            },
            editPortHandleCancel(e) {
                console.log('Clicked cancel button');
                this.editPortVisible = false;
            },
            configItemHandleCancel(e) {
                console.log('Clicked cancel button');
                this.configItemVisible = false;
            },
            editConfigItemHandleCancel(e) {
                console.log('Clicked cancel button');
                this.editConfigItemVisible = false;
            },
            handleTableChange(pagination, filters, sorter) {
                this.grid.pagination.current = pagination.current;
                this.grid.pagination.pageSize = pagination.pageSize;
                this.fetch();
            },
            fetch() {
                const that = this;
                that.loading = true;
                getFetch("/api/appEnv?" + that.grid.params + "&page=" + that.grid.pagination.current + "&size=" + that.grid.pagination.pageSize).then((data) => {
                    const pagination = { ...that.grid.pagination };
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    pagination.total = data.data.totalElements;
                    that.loading = false;
                    that.grid.data = data.data.content;
                    that.grid.pagination = pagination;
                });
            },
            handlePortTableChange(pagination, filters, sorter) {
                this.portGrid.pagination.current = pagination.current;
                this.portGrid.pagination.pageSize = pagination.pageSize;
                this.fetchMappingPort();
            },
            handleConfigItemTableChange(pagination, filters, sorter) {
                this.configItemGrid.pagination.current = pagination.current;
                this.configItemGrid.pagination.pageSize = pagination.pageSize;
                this.fetchConfigItem();
            },
            fetchMappingPort() {
                const that = this;
                const appEnvId = that.grid.selectedRows[0].id;
                that.portGrid.loading = true;
                getFetch("/api/appEnvPort?appEnv.id=" + appEnvId + "&page=" + that.portGrid.pagination.current + "&size=" + that.portGrid.pagination.pageSize).then((data) => {
                    const pagination = { ...that.portGrid.pagination };
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    pagination.total = data.data.totalElements;
                    that.portGrid.loading = false;
                    that.portGrid.data = data.data.content;
                    that.portGrid.pagination = pagination;
                });
            },
            fetchConfigItem() {
                const that = this;
                const appEnvId = that.grid.selectedRows[0].id;
                that.configItemGrid.loading = true;
                getFetch("/api/appEnvConfigItem?appEnv.id=" + appEnvId + "&page=" + that.configItemGrid.pagination.current + "&size=" + that.configItemGrid.pagination.pageSize).then((data) => {
                    const pagination = { ...that.configItemGrid.pagination };
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    pagination.total = data.data.totalElements;
                    that.configItemGrid.loading = false;
                    that.configItemGrid.data = data.data.content;
                    that.configItemGrid.pagination = pagination;
                });
            }
        },
    }
</script>
